package main

import (
	"log"
	"net/http"
	"fmt"
)

const(
	PAGE_INIT = 1
	PAGE_ERROR = 2
	PAGE_SUCCESS = 3

)

const (
	htmlTop = `
	<!DOCTYPE html>
		<html lang="en">
		<head>
		    <meta charset="UTF-8">
		    <title>Title</title>
		</head>
		<body>
	`
	formBegin = `
		<form action="/" method="POST">
			<table>
			    <tr>
				<td>
				    存入金额：
				</td>
				<td>
				    <input type="text" name="saveMoney">元
				</td>
			    </tr>
			    <tr>
				<td>
				    年利率：
				</td>
				<td>
				    <input type="text" name="interestRate">%
				</td>
			    </tr>
			    <tr>
				<td>
				    存入时间：
				</td>
				<td>
				    <input type="text" name="day">天
				</td>
			    </tr>
			    <tr>
				<td colspan="2">
				    <input type="submit" name="calculate" value="计算">
				</td>
			    </tr>
			    <tr>
				<td colspan="2">
				    收益金额：
	`
	formEnd = `
				</td>
			    </tr>
			</table>
		    </form>
	`
	htmlBottom = `
		</body>
	</html>
	`
	error = "<p>%s → %s</p>"
)

func main() {
	log.Println("start server begin")
	http.HandleFunc("/", homePage)
	log.Println("setup server port")
	if err := http.ListenAndServe(":9002", nil); err != nil {
		log.Fatal("failed to start server", err)
	}
	log.Println("start server end")
}

func homePage(writer http.ResponseWriter, request *http.Request) {
	err := request.ParseForm()
	fmt.Fprint(writer, htmlTop, formBegin)
	if err != nil {
		fmt.Fprintf(writer, error, err)
	} else {
		saveMoney,interestRate,day,page := processRequest(request)
		if page == PAGE_SUCCESS{
			answer := calculateResult(saveMoney,interestRate,day)
			fmt.Fprintf(writer,answer)
		}else if page == PAGE_ERROR {
			fmt.Fprintf(writer,error)
		}
	}
	fmt.Fprint(writer, formEnd ,htmlBottom)
}

func calculateResult (saveMoney,interestRate,day string) string {
	return saveMoney + " * " + interestRate + "% // 365 * " + day + " = "
}

func processRequest(request *http.Request) (string,string,string,int) {
	//saveMoney	interestRate	day	calculate
	for index, key := range []string{"saveMoney", "interestRate", "day"} {
		fmt.Println(index)
		if slice, found := request.Form[key]; found && len(slice) > 0 {
			fmt.Println(request.Form["saveMoney"])
			fmt.Println(request.Form["interestRate"])
			fmt.Println(request.Form["day"])
			saveMoney,interestRate,day := getFormatInputText(request.Form)
			if len(saveMoney) > 0 && len(interestRate) > 0 && len(day) > 0{
				return saveMoney,interestRate,day,PAGE_SUCCESS
			} else {
				return saveMoney,interestRate,day,PAGE_ERROR
			}
		}
	}
	return "","","",PAGE_INIT
}

func getFormatInputText(form map[string][]string) (string,string,string) {
	fmt.Println(form["saveMoney"][0])
	fmt.Println(form["interestRate"][0])
	fmt.Println(form["day"][0])
	return fmt.Sprint(form["saveMoney"][0]),fmt.Sprint(form["interestRate"][0]),fmt.Sprint(form["day"][0])
}